<?php
namespace x;
use x\my\Jump;
class App
{
    public $version  = '0.0.1';
    public $debug    = true;
    public $pathinfo = null;
    public $config   = [];
    public $m = 'www';
    public $c = 'index';
    public $a = 'init';
    public $container;
    /**
     * 执行应用程序
     * @access public
     */
    public function run()
    {
        $this->config();
        $this->route();
        $this->autoload();
        $this->container = Container::getInstance();
        $this->controller();
    }
    /**
     * 实例化控制器
     * 执行程序
     */
    public function controller()
    {
        if($this->c=='jump'){
            $this->a=='success' ? Jump::success() : Jump::error();
            return;
        }
        $className = 'app\\'.strtolower($this->m).'\\controller\\'.ucwords($this->c);
        $class = $this->container->make($className);
        $action = ucwords($this->a);
        $vars = [];
        return $this->container->invokeMethod([$class, $action], $vars);
    }

    /**
     * 引入model文件
     * @return [type] [description]
     */
    public function model($name, $layer=''){
        switch ($layer) {
            case '':
                $class = 'app\\'.$this->m.'\\model\\'.ucfirst($name);
                break;
            case 'c':
                $class = 'app\\common\\model\\'.ucfirst($name);
                break;
            case 'xcom':
                $class = 'xcom\\model\\'.ucfirst($name);
                break;
            default:
                $class = 'x\\'.$layer.'\\model\\'.ucfirst($name);
                break;
        }
        return Container::get($class);
    }

    //加载配置
    public function config(){
        $this->debug = env('debug');

        if (!$this->debug) {
            ini_set('display_errors', 'Off');
        } elseif (PHP_SAPI != 'cli') {
            //重新申请一块比较大的buffer
            if (ob_get_level() > 0) {
                $output = ob_get_clean();
            }
            ob_start();
            if (!empty($output)) {
                echo $output;
            }
        }
        // 设置系统时区
        date_default_timezone_set(env('default_timezone'));
    }

    //设置路由
    public function route(){
        $this->pathinfo();
        $arr    = array_merge(array_filter(explode("/",$this->pathinfo)),[]);
        $host = explode(":",$_SERVER['HTTP_HOST']);

        //获取模块
        if(G::$domain_config['module']){
          $module = array_search(DOMAIN, G::$domain_config['module']);
          //t(['域名'=>DOMAIN, '配置'=>G::$domain_config]);
          if(!$module) exit(DOMAIN.' is not configured');

          $this->m = strtolower($module);
          if(isset($arr[0])) $this->c = strtolower($arr[0]);
          if(isset($arr[1])) $this->a = strtolower($arr[1]);
        }else{
          if(isset($arr[0])) $this->m = strtolower($arr[0]);
          if(isset($arr[1])) $this->c = strtolower($arr[1]);
          if(isset($arr[2])) $this->a = strtolower($arr[2]);
        }
        $this->a = str_ireplace(['.','html','php','htmls','html'],'',$this->a);
        //t([$arr, $module,$this->m,$this->c,$this->a]);
    }

    //自动加载文件
    public function autoload(){
        $dir = APP_PATH.'autoload';
        if (false != ($handle = opendir ( $dir ))) {
            while ( false !== ($file = readdir ( $handle )) ) {
                if ($file != "." && $file != ".." && strpos($file,".")) {
                    include_once APP_PATH.'autoload/'.$file;
                }
            }
            closedir ( $handle );
        }
    }

    /**
     * 获取当前请求URL的pathinfo信息（含URL后缀）
     * @access public
     * @return string
     */
    public function pathinfo()
    {
        if (is_null($this->pathinfo)) {
            if (isCli()) {
                // CLI模式下 index.php module/controller/action/params/...
                $_SERVER['PATH_INFO'] = isset($_SERVER['argv'][1]) ? $_SERVER['argv'][1] : '';
            }
            // 分析PATHINFO信息
            if (!isset($_SERVER['PATH_INFO'])) {
                foreach (['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REQUEST_URI'] as $type) {
                    if (!empty($_SERVER[$type])) {
                        if(0 === strpos($_SERVER[$type], $_SERVER['SCRIPT_NAME'])){
                            $_SERVER['PATH_INFO'] = substr($_SERVER[$type], strlen($_SERVER['SCRIPT_NAME']));
                        }else{
                            $_SERVER['PATH_INFO'] = $_SERVER[$type];
                        }
                        break;
                    }
                }
            }
            //首页403问题
            if(!isset($_SERVER['PATH_INFO']) or $_SERVER['PATH_INFO']=='403.html'){
                $_SERVER['PATH_INFO'] = '/';
            }
            $_SERVER['PATH_INFO'] = str_replace(['/index.php'], '', $_SERVER['PATH_INFO']);
            $this->pathinfo = empty($_SERVER['PATH_INFO']) ? '/' : ltrim($_SERVER['PATH_INFO'], '/');
            $this->pathinfo = preg_replace("/([\s\S]*)([\?]+)([\s\S]*)/","$1",$this->pathinfo);
            $this->pathinfo = preg_replace("/([\s\S]*)([\.]+)([\s\S]*)/","$1",$this->pathinfo);
            $this->pathinfo = preg_replace("/([\s\S]*)([\#]+)([\s\S]*)/","$1",$this->pathinfo);
        }
        return $this->pathinfo;
    }
}
